package com.yyfax.pay.order.data.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.yyfax.commons.lang.DateUtil;
import com.yyfax.framework.exception.YYException;
import com.yyfax.framework.service.CacheService;
import com.yyfax.framework.service.impl.BaseServiceImpl;
import com.yyfax.framework.yyfax.enums.YesNoEnum;
import com.yyfax.pay.common.constants.PayConstants;
import com.yyfax.pay.common.enums.PayRspCodeEnum;
import com.yyfax.pay.common.enums.PayoutBatchStepEnum;
import com.yyfax.pay.order.data.dao.PayoutBatchOrderDao;
import com.yyfax.pay.order.data.service.PayoutBatchOrderLogService;
import com.yyfax.pay.order.data.service.PayoutBatchOrderService;
import com.yyfax.pay.order.data.service.PayoutOrderService;
import com.yyfax.pay.order.model.po.PayoutBatchOrderLogPO;
import com.yyfax.pay.order.model.po.PayoutBatchOrderPO;
import com.yyfax.pay.order.model.vo.PayBusiIdVO;
import com.yyfax.pay.order.model.vo.PayoutBatchOrderVO;
import com.yyfax.pay.order.model.vo.PayoutOrderVO;

/**
 * 批量代付订单服务实现
 *
 * @author buyi
 * @date 2017-04-12 11:09:15
 * @since 1.0.0
 */
@Service
public class PayoutBatchOrderServiceImpl extends BaseServiceImpl implements PayoutBatchOrderService {
	private Logger logger = LoggerFactory.getLogger(getClass());

	private final String PAYOUT_BATCH_ORDER_ID_PREFIX = "B";
	private final String PAYOUT_BATCH_ORDER_ID_CONCAT = "_";

	@Autowired
	private PayoutBatchOrderDao payoutBatchOrderDao;

	@Autowired
	private PayoutBatchOrderLogService payoutBatchOrderLogService;

	@Autowired
	private PayoutOrderService payoutOrderService;
	
	@Autowired
	private PayConstants payConstants;

	public PayoutBatchOrderServiceImpl(@Qualifier("payCacheService") CacheService cacheService) {
		super(cacheService);
	}

	/**
	 * 获取业务主键
	 * 
	 * @author buyi
	 * @date 2017-04-20 09:40:30
	 * @since v1.0.0
	 * @param merchantCode
	 * @param orderId
	 * @return
	 */
	private String getPayoutBatchOrderId(String merchantCode, String orderId) {
		return PAYOUT_BATCH_ORDER_ID_PREFIX.concat(PAYOUT_BATCH_ORDER_ID_CONCAT).concat(merchantCode).concat(PAYOUT_BATCH_ORDER_ID_CONCAT)
				.concat(orderId);
	}

	@Override
	public PayBusiIdVO resolverPayoutBatchOrderId(String payoutBatchOrderId) throws YYException {
		if (StringUtils.isBlank(payoutBatchOrderId)) {
			return null;
		}

		String[] split = payoutBatchOrderId.split(PAYOUT_BATCH_ORDER_ID_CONCAT);

		if (split.length < 3) {
			throw new YYException(PayRspCodeEnum.COMMON_ERROR_PARAMETER_INVALID, "参数payoutBatchOrderId异常,封装规则PREFIX_MERCHANTCODE_ORDERID");
		}

		return new PayBusiIdVO(split[1], split[2]);
	}

	@Override
	public PayoutBatchOrderPO queryByIdAndMerchantCode(int id, String merchantCode) throws Exception {
		if (id <= 0 && StringUtils.isBlank(merchantCode)) {
			logger.debug("参数 'id' 不能为0，且 'merchantCode' 不能为空 ");
			return null;
		}

		return payoutBatchOrderDao.selectByIdAndMerchantCode(id, merchantCode);
	}

	@Override
	public PayoutBatchOrderPO queryByMerchantCodeAndOrderId(String merchantCode, String orderId) throws Exception {
		if (StringUtils.isBlank(merchantCode) && StringUtils.isBlank(orderId)) {
			logger.debug("参数  orderId/merchantCode 不能为空 ");
			return null;
		}

		return payoutBatchOrderDao.selectByMerchantCodeAndOrderId(merchantCode, orderId);
	}

	@Override
	public String saveAndReturnBusiKey(PayoutBatchOrderPO po) throws Exception {
		if (po == null) {
			logger.debug("参数po为空，返回-1");
			return null;
		}

		String payoutBatchOrderId = getPayoutBatchOrderId(po.getMerchantCode(), po.getOrderId());
		po.setPayoutBatchOrderId(payoutBatchOrderId);

		if (StringUtils.isBlank(po.getExpireTime())) { // 如果没有传订单过期时间，则默认生成过期时间
			long expireTime = DateUtil.str2DateTime(po.getOrderTime()).getTime() + payConstants.getDefaultExpireTime();
			po.setExpireTime(DateUtil.milli2str(expireTime));
		}

		po.setCreateTime(DateUtil.getCurrentDateTime());
		payoutBatchOrderDao.insertReturnPK(po);

		return payoutBatchOrderId;
	}

	@Override
	public PayoutBatchOrderVO queryPayoutBatchOrderVO(String merchantCode, String orderId) throws Exception {
		PayoutBatchOrderPO payoutBatchOrderPO = queryByMerchantCodeAndOrderId(merchantCode, orderId);
		if (payoutBatchOrderPO == null) {
			return null;
		}

		PayoutBatchOrderVO payoutBatchOrderVo = new PayoutBatchOrderVO();
		BeanUtils.copyProperties(payoutBatchOrderPO, payoutBatchOrderVo);

		List<PayoutBatchOrderLogPO> payoutBatchOrderLogPOs = payoutBatchOrderLogService.queryListByPayoutBatchOrderId(merchantCode,
				payoutBatchOrderPO.getPayoutBatchOrderId());
		payoutBatchOrderVo.setPayoutBatchOrderLogPOs(payoutBatchOrderLogPOs);

		payoutBatchOrderVo.setClose(false);

		// 迭代判断批量代付订单关闭状态和响应结果
		if (payoutBatchOrderLogPOs != null) {
			for (PayoutBatchOrderLogPO payoutBatchOrderLogPO : payoutBatchOrderLogPOs) {
				if ((PayoutBatchStepEnum.STEP2_PAY_RESULT.isValue(payoutBatchOrderLogPO.getStep())
						|| PayoutBatchStepEnum.STEP3_CHECK_RESULT.isValue(payoutBatchOrderLogPO.getStep()))
						&& PayRspCodeEnum.SUCCESS.isValue(payoutBatchOrderLogPO.getResultCode())) {
					// 步骤为结果响应或对账，且状态为成功
					payoutBatchOrderVo.setResultCode(payoutBatchOrderLogPO.getResultCode());
					payoutBatchOrderVo.setResultMsg(payoutBatchOrderLogPO.getResultMsg());
				}

				if (YesNoEnum.YES.isValue(payoutBatchOrderLogPO.getClosed())) {
					payoutBatchOrderVo.setClose(true);
				}
			}
		}

		List<PayoutOrderVO> payoutOrderVOs = payoutOrderService.queryPayoutOrderVoList(merchantCode, payoutBatchOrderPO.getPayoutBatchOrderId());
		payoutBatchOrderVo.setPayoutOrderVOs(payoutOrderVOs);

		return payoutBatchOrderVo;
	}

	@Override
	public int modify(PayoutBatchOrderPO payoutBatchOrderPO) throws Exception {
		if(payoutBatchOrderPO == null){
			return -1;
		}
		
		return payoutBatchOrderDao.update(payoutBatchOrderPO);
	}
}
